<template>
  <div class="incoming-inspection">
    <!-- 搜索区 -->
    <el-card class="mb-4" shadow="never">
      <el-form :inline="true" :model="searchForm" size="small">
        <el-form-item label="检验单编号">
          <el-input v-model="searchForm.code" clearable placeholder="检验单编号" />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="searchForm.material" clearable placeholder="物料名称" />
        </el-form-item>
        <el-form-item label="检测结果">
          <el-select v-model="searchForm.result" clearable placeholder="全部"  style="width:120px;margin-right:10px;">
            <el-option label="合格" value="合格" />
            <el-option label="不合格" value="不合格" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="openDialog('add')">新增检验单</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 检验单表格 -->
    <el-table :data="filteredData" border style="width:100%;">
      <el-table-column prop="code" label="检验单编号" width="140" />
      <el-table-column prop="material" label="物料名称" width="150" />
      <el-table-column prop="batchNo" label="批次号" width="120" />
      <el-table-column prop="quantity" label="数量" width="80" />
      <el-table-column prop="failCount" label="不合格数量" width="110" />
      <el-table-column prop="result" label="检测结果" width="100">
        <template #default="{ row }">
          <el-tag :type="row.result==='合格'?'success':'danger'">{{ row.result }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="检测日期" width="120" />
      <el-table-column label="合格率" width="90">
        <template #default="{ row }">
          {{ calcPassRate(row) }}%
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row, $index }">
          <el-button size="small" @click="openDialog('edit', row, $index)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogMode==='add'?'新增检验单':'编辑检验单'" v-model="showDialog" width="430px">
      <el-form :model="dialogForm" :rules="dialogRules" ref="dialogFormRef" label-width="90px">
        <el-form-item label="检验单编号" prop="code">
          <el-input v-model="dialogForm.code" :disabled="dialogMode==='edit'" />
        </el-form-item>
        <el-form-item label="物料名称" prop="material">
          <el-input v-model="dialogForm.material" />
        </el-form-item>
        <el-form-item label="批次号" prop="batchNo">
          <el-input v-model="dialogForm.batchNo" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="dialogForm.quantity" :min="1" style="width:100%;" />
        </el-form-item>
        <el-form-item label="不合格数量" prop="failCount">
          <el-input-number v-model="dialogForm.failCount" :min="0" :max="dialogForm.quantity" style="width:100%;" />
        </el-form-item>
        <el-form-item label="检测结果" prop="result">
          <el-select v-model="dialogForm.result">
            <el-option label="合格" value="合格" />
            <el-option label="不合格" value="不合格" />
          </el-select>
        </el-form-item>
        <el-form-item label="检测日期" prop="date">
          <el-date-picker v-model="dialogForm.date" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width:100%;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitDialog">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

const pageSize = 8
const currentPage = ref(1)

// 模拟数据
const allData = ref(generateMock())
function generateMock() {
  const mat = ['对乙酰氨基酚', '头孢拉定原料', '维生素C粉', '葡萄糖', '乳糖', '硬脂酸镁', '阿莫西林', '氯化钠']
  const res = ['合格', '不合格']
  let arr = []
  for (let i = 0; i < 17; i++) {
    const qty = Math.floor(Math.random()*1000)+100
    const fail = Math.random()<0.13 ? Math.floor(Math.random()*qty*0.1) : 0
    arr.push({
      code: `JCYJ${20230601+i}`,
      material: mat[i%mat.length],
      batchNo: 'BN' + (1000+i),
      quantity: qty,
      failCount: fail,
      result: fail===0 ? '合格' : '不合格',
      date: `2025-06-${String(i%29+1).padStart(2,'0')}`,
    })
  }
  return arr
}

// 搜索相关
const searchForm = reactive({ code:'', material:'', result:'' })
const filteredData = computed(() =>
  allData.value.filter(row =>
    (!searchForm.code || row.code.includes(searchForm.code)) &&
    (!searchForm.material || row.material.includes(searchForm.material)) &&
    (!searchForm.result || row.result===searchForm.result)
  )
)
const pagedData = computed(() => {
  const start = (currentPage.value-1)*pageSize
  return filteredData.value.slice(start, start+pageSize)
})
function handleSearch(){}
function resetSearch(){
  searchForm.code = ''
  searchForm.material = ''
  searchForm.result = ''
  currentPage.value = 1
}

// 合格率自动统计
function calcPassRate(row){
  if(!row.quantity) return 0
  return ((row.quantity - row.failCount)/row.quantity*100).toFixed(1)
}

// 增删改相关
const showDialog = ref(false)
const dialogMode = ref('add') // add / edit
const dialogForm = reactive({
  code:'', material:'', batchNo:'', quantity:1, failCount:0, result:'合格', date:''
})
const dialogRules = {
  code: [{ required: true, message: '必填', trigger: 'blur' }],
  material: [{ required: true, message: '必填', trigger: 'blur' }],
  batchNo: [{ required: true, message: '必填', trigger: 'blur' }],
  quantity: [{ required: true, message: '必填', trigger: 'blur' }],
  failCount: [{ required: true, message: '必填', trigger: 'blur' }],
  result: [{ required: true, message: '必填', trigger: 'change' }],
  date: [{ required: true, message: '必填', trigger: 'change' }]
}
const dialogFormRef = ref()
let editingIdx = -1
function openDialog(mode, row, idx){
  dialogMode.value = mode
  if(mode==='add'){
    Object.assign(dialogForm, {
      code:'', material:'', batchNo:'', quantity:1, failCount:0, result:'合格', date:''
    })
  }else{
    Object.assign(dialogForm, { ...row })
    editingIdx = idx
  }
  showDialog.value = true
  nextTick(()=>dialogFormRef.value && dialogFormRef.value.clearValidate())
}
function submitDialog(){
  dialogFormRef.value.validate(valid=>{
    if(!valid) return
    if(dialogMode.value==='add'){
      allData.value.unshift({...dialogForm})
      ElMessage.success('新增成功')
    }else{
      allData.value.splice(editingIdx,1,{...dialogForm})
      ElMessage.success('编辑成功')
    }
    showDialog.value = false
  })
}
function handleDelete(idx){
  allData.value.splice(idx,1)
  ElMessage.success('已删除')
}
</script>

<style scoped>
.incoming-inspection {
  padding: 20px 16px;
}
.mb-4 { margin-bottom: 16px;}
.mt-2 { margin-top: 12px;}
</style>
